<template>
  <div class="verify-code">
    <canvas ref="canvas" @click="refreshCode"></canvas>
    <p @click="refreshCode">换一张</p>
  </div>
</template>

<script setup>
import { ref, onMounted, defineEmits } from 'vue';

const emit = defineEmits(['update:code']);
const canvas = ref(null);
const code = ref('');

const generateCode = () => {
  const chars = '1234567890';
  let result = '';
  for (let i = 0; i < 4; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

const getRandomColor = () => {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
};

const drawCode = () => {
  const ctx = canvas.value.getContext('2d');
  ctx.clearRect(0, 0, canvas.value.width, canvas.value.height);
  ctx.font = '20px Arial';

  // 绘制验证码字符
  for (let i = 0; i < code.value.length; i++) {
    ctx.fillStyle = getRandomColor();
    ctx.fillText(code.value[i], 10 + i * 20, 30);
  }

  // 绘制干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = getRandomColor();
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.value.width, Math.random() * canvas.value.height);
    ctx.lineTo(Math.random() * canvas.value.width, Math.random() * canvas.value.height);
    ctx.stroke();
  }
};

const refreshCode = () => {
  code.value = generateCode();
  drawCode();
  emit('update:code', code.value);
};

onMounted(() => {
  canvas.value.width = 100;
  canvas.value.height = 40;
  refreshCode();
});
</script>

<style>
.verify-code {
  display: flex;
  align-items: center;
}

canvas {
  border: 1px solid #aaa;
  cursor: pointer;
  margin-right: 10px;
}
</style>




